package com.ridbor001.demo.servlet;

import com.ridbor001.demo.bean.*;
import com.ridbor001.demo.service.RDBCourseService;
import com.ridbor001.demo.service.RDBStudentCourseService;
import com.ridbor001.demo.service.RDBStudentService;
import com.ridbor001.demo.service.RDBTeacherService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@WebServlet("/courseManage")
public class RDBCourseManageServlet extends HttpServlet {
    @lombok.SneakyThrows
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        RDBCourseService rdbCourseService = new RDBCourseService();
        RDBStudentService rdbStudentService = new RDBStudentService();
        RDBTeacherService rdbTeacherService = new RDBTeacherService();
        RDBStudentCourseService rdbStudentCourseService = new RDBStudentCourseService();
        req.setCharacterEncoding("UTF-8");

        // 权限验证
        RDBUser user = (RDBUser) req.getSession().getAttribute("user");
        if (user == null || !user.isAdmin()) {
            resp.sendError(403, "无操作权限");
            return;
        }

        // 获取表单参数
        String courseName = req.getParameter("courseName");
        String term = req.getParameter("term");
        String studentIdsStr = req.getParameter("studentIds");
        String[] studentIds = studentIdsStr != null ? studentIdsStr.split(",") : new String[0];



        // 参数检查
        if (courseName == null || courseName.isEmpty() || term == null || term.isEmpty()) {
            resp.sendError(400, "课程名称和学期不能为空");
            return;
        }
        String teacherId = req.getParameter("teacherId");
        if (teacherId == null || teacherId.isEmpty()) {
            resp.sendError(400, "教师不能为空");
            return;
        }
        if (!rdbTeacherService.teacherExists(teacherId)) {
            resp.sendError(400, "教师不存在");
            return;
        }

        // 生成课程ID
        String courseId = UUID.randomUUID().toString();
        RDBCourse newCourse = new RDBCourse(courseId, courseName, term, teacherId);

        // 保存课程和关联学生（在同一个事务中）
        try {
            rdbCourseService.addCourse(newCourse);
            // 建立学生-课程关联
            for (String studentId : studentIds) {
                if (rdbStudentService.studentExists(studentId)) {
                    // 添加学生选课关系到数据库（关系表）
                    rdbStudentCourseService.addStudentToCourse(studentId, courseId);
                }
            }
        } catch (SQLException e) {
            // 出现异常，应该回滚事务（假设在RDBDataStore内部使用了事务）
            throw new ServletException("保存课程失败: " + e.getMessage(), e);
        }

        // 重定向到课程列表页面
        resp.sendRedirect(req.getContextPath() + "/rDBDashboard.jsp");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        RDBStudentService rdbStudentService = new RDBStudentService();
        RDBTeacherService rdbTeacherService = new RDBTeacherService();

        List<RDBTeacher> teachers = null;
        try {
            teachers = rdbTeacherService.getAllTeachers();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        req.setAttribute("teachers", teachers);

        try {
            // 从数据库加载所有学生数据
            List<RDBStudent> students = rdbStudentService.getAllStudents();
            req.setAttribute("students", students);

            // 转发到添加课程页面
            req.getRequestDispatcher("/rDBCourseAdd.jsp").forward(req, resp);

        } catch (SQLException e) {
            // 错误处理
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "获取学生列表失败");
        }
    }
}